package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R save(@RequestBody SetmealDto setmealDto){
        log.info("套餐信息:{}",setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("添加套餐成功");
    }

    @GetMapping("/page")
    public R page(int page,int pageSize,String name){
        //构造分页构造器
        Page<Setmeal> pageInfo = new Page(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //添加条件
        lqw.like(StringUtils.isNotEmpty(name),Setmeal::getName,name);
        //添加排序条件:更新时间降序
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        setmealService.page(pageInfo,lqw);


        //获得套餐的基本信息和分类名称
        Page<SetmealDto> resultPage = new Page<>();
        //把原始的pageInfo的数据拷贝至resultPage，排除records。拷贝上：总数据量，当前页，每页显示数量，总页数
        //BeanUtils.copyProperties(pageInfo,resultPage);
        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> resultList = records.stream().map(setmeal -> {
            //循环一遍构建一个Dto对象
            SetmealDto setmealDto = new SetmealDto();
            //把套餐数组拷贝到Dto中
            BeanUtils.copyProperties(setmeal, setmealDto);
            //根据分类id查询分类对象
            Category category = categoryService.getById(setmealDto.getCategoryId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());

        resultPage.setRecords(resultList);

        return R.success(resultPage);
    }

    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        log.info("要删除的id为:{}", ids);
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }
}    